#include <iostream>
#include <sys/shm.h>
#include <sys/ipc.h>
#include <string>
#include <sys/stat.h>
#include <cstdio>
#include <unistd.h>

const std::string pathname = "/home/fy/code/ShareMemCom";
const int projid = 0x66;
const int msize = 4096;
const int mode = 0600;

class ShareMemory
{
    int CreateShmHelper(int flag)
    {
        _key = ftok(pathname.c_str(), projid);
        if (_key == -1)
        {
            std::cout << "_key error" << std::endl;
            return 1;
        }
        _shmid = shmget(_key, msize, flag);
        if (_shmid == -1)
        {
            perror("GetShm error");
            return 2;
        }
        return 0;
    }

public:
    ShareMemory()
        : _key(-1), _shmid(-1), _addr(nullptr)
    {}

    void GetShm()
    {
        CreateShmHelper(IPC_CREAT);
    }

    void CreatShm()
    {
        if (_shmid == -1)
        {
            umask(0);
            CreateShmHelper(IPC_EXCL | IPC_CREAT | mode);
        }
    }

    void AttachShm()
    {
        _addr = shmat(_shmid, nullptr, 0);
        if ((long long)_addr == -1)
        {
            std::cout << "Attach error" << std::endl;
            return ;
        }
    }

    void DetachShm()
    {
        if(_addr != nullptr)
        shmdt(_addr);
    }

    void DeleteShm()
    {
        shmctl(_shmid, IPC_RMID, nullptr);
    }

    void* GetAddr()
    {
        return _addr;
    }

    ~ShareMemory()
    {
    }

private:
    int _key;
    int _shmid;
    void *_addr;
};

ShareMemory mem;

struct data
{
    char status[32];
    char lasttime[48];
    char image[4000];
};